<template>
  <!-- 收货地址 -->
  <van-contact-card
    type="edit"
    :name="`${address.consignee} ${address.region_text}`"
    :tel="address.mobile"
    @click="AddressShow = true"
  />

  <!-- 商品卡片 -->
  <van-card
    v-for="item in OrderProductData"
    :thumb="item.products.thumb_text"
    :key="item.id"
  >
    <template #title>
      <router-link
        :to="{ path: '/product/info', query: { proid: item.proid } }"
      >
        <div class="title">{{ item.products.name }}</div>
      </router-link>
    </template>

    <!-- 卡片的插槽部分 -->
    <template #desc v-if="item.attrs">
      <van-tag
        v-for="(attr, index) in JSON.parse(item.attrs)"
        :key="index"
        class="tag"
        type="primary"
        >{{ attr.value }}</van-tag
      >
    </template>

    <!-- 卡片的插槽部分 -->
    <template #desc v-else>
      <van-tag class="tag" type="danger">无商品规格</van-tag>
    </template>

    <template #price>
      <div class="price-box">
        <div class="price">
          <p>单价：￥{{ item.price }}</p>
          <p>商品总价：￥ {{ item.total }}</p>
        </div>
        <div class="num">x{{ item.pronum }}</div>
      </div>
    </template>

    <template #footer v-if="order.status >= '3'">
      <van-button type="warning" size="mini" @click="OnCommentChange(item)">
        {{ item.comment ? "查看评价" : "立即评价" }}
      </van-button>
    </template>
  </van-card>

  <!-- 订单信息 -->
  <van-cell title="订单号" :value="order.code" />
  <van-cell
    title="优惠金额"
    v-if="order.coupon"
    :value="`￥${order.coupon_price}`"
  />
  <van-cell title="订单总价" :value="`￥${order.amount}`" />
  <van-cell title="支付方式" :value="order.pay_text" />
  <van-cell title="订单状态" :value="order.status_text" />
  <van-cell title="下单时间" :value="order.createtime_text" />
  <van-cell title="订单描述" :value="order.remark" />

  <!-- 操作按钮组 -->
  <div class="actions">
    <van-button square hairline type="primary" size="large"
      >在线客服</van-button
    >

    <van-button
      v-if="order.status == '1'"
      square
      hairline
      type="danger"
      size="large"
      @click="OnRefund(order.id)"
      >申请退款</van-button
    >

    <van-button
      v-if="order.status == '2'"
      square
      hairline
      type="success"
      size="large"
      @click="OnConfirmReceive(order.id)"
      >确认收货</van-button
    >
    <van-button
      v-if="order.status == '2'"
      square
      hairline
      type="warning"
      size="large"
      @click="ToExpressInfo(order.id)"
      >物流详情</van-button
    >
  </div>

  <!-- 收货地址弹出层 -->
  <van-popup
    v-model:show="AddressShow"
    position="bottom"
    round
    style="padding-top: 4px"
  >
    <van-form>
      <van-field v-model="address.consignee" label="收件人" readonly />
      <van-field v-model="address.mobile" label="手机号码" readonly />
      <van-field v-model="address.region_text" label="所在地区" readonly />
      <van-field v-model="address.address" label="详细地址" readonly />
      <van-field v-model="address.status_text" label="是否默认地址" readonly />
      <div style="width: 80%; margin: 1em auto">
        <van-button round block type="primary" @click="AddressShow = false"
          >关闭</van-button
        >
      </div>
    </van-form>
  </van-popup>

  <!-- 评论弹出层 -->
  <van-popup
    v-model:show="CommentShow"
    position="bottom"
    round
    style="height: 60%; padding-top: 4px"
  >
    <van-form @submit="OnCommentSubmit">
      <van-field
        label="评论内容"
        type="textarea"
        rows="3"
        v-model="CommentData.comment"
        placeholder="请输入评论内容"
        :rules="[{ required: true, message: '请输入评论内容' }]"
        :readonly="CommentData.status"
      />

      <van-field label="评分">
        <template #input>
          <van-rate v-model="CommentData.rate" :readonly="CommentData.status" />
        </template>
      </van-field>

      <van-field label="上传图集">
        <template #input>
          <van-uploader
            v-model="thumbs"
            multiple
            :max-count="9"
            :readonly="CommentData.status"
            :deletable="!CommentData.status"
          />
        </template>
      </van-field>

      <div style="width: 80%; margin: 2em auto">
        <van-button
          v-if="CommentData.status"
          round
          block
          color="linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)"
          @click="CommentShow = false"
          >关闭弹框</van-button
        >
        <van-button
          v-else
          round
          block
          color="linear-gradient(160deg, #0093E9 0%, #80D0C7 100%)"
          native-type="submit"
          >提交评价</van-button
        >
      </div>
    </van-form>
  </van-popup>

  <!-- 申请退款弹出层 -->
  <van-popup
    v-model:show="ApplyShow"
    position="bottom"
    round
    :style="{ paddingBottom: '20px' }"
  >
    <van-picker
      title="退款原因"
      :columns="RemarkList"
      @cancel="ApplyShow = false"
      @confirm="OnRefundApply"
    />
  </van-popup>
</template>

<script setup>
// this
const { proxy } = getCurrentInstance();
// 接收地址栏参数 订单id
const orderid = ref(proxy.$route.query.orderid ?? 0);
// 登录信息
const business = proxy.$business;
// 订单数据
const order = ref({});
// 订单商品数据
const OrderProductData = ref([]);
// 收货地址数据
const address = ref({});
// 收货地址弹出层
const AddressShow = ref(false);
// 评论弹出层
const CommentShow = ref(false);
// 申请退款弹出层
const ApplyShow = ref(false);
// 备注数据
const RemarkList = ref([
  { text: "拍错了", value: "拍错了" },
  { text: "地址有误", value: "地址有误" },
  { text: "不想要了", value: "不想要了" },
  { text: "参数选错了", value: "参数选错了" },
  { text: "选择其他的", value: "选择其他的" },
]);
// 评论数据
const CommentData = ref({
  id: 0,
  rate: 0,
  comment: "",
  status: false, // 评论状态
});
// 评价图片
const thumbs = ref([]);

// 挂载前钩子
onBeforeMount(() => GetInfoData());

// 获取订单详情数据
const GetInfoData = async () => {
  // 组装参数
  const params = {
    orderid: orderid.value,
    busid: business.value.id,
  };
  // 发起请求
  const result = await proxy.$http.post({
    url: "order/info",
    params,
  });
  // 处理请求结果
  if (result.code === 1) {
    order.value = result.data.order;
    OrderProductData.value = result.data.OrderProductData;
    address.value = result.data.address;
    // 如果有使用优惠券
    if (order.value.coupon) {
      // 购买的商品总价
      let amount = 0;
      // 循环计算
      OrderProductData.value.map((product) => {
        amount += parseFloat(product.total);
      });
      // 优惠价格
      order.value.coupon_price = (
        amount - parseFloat(order.value.amount)
      ).toFixed(2);
    }
  } else {
    proxy.$fail({
      message: result.msg,
      onClose: () => {
        proxy.$router.back();
      },
    });
  }
};

// 申请退款
const OnRefund = (id) => {
  ApplyShow.value = true;
  orderid.value = id;
};

// 确认申请退款
const OnRefundApply = async (value) => {
  // 组装参数
  const params = {
    id: orderid.value,
    busid: business.value.id,
    refundreason: value.selectedValues[0],
  };
  // 发起请求
  const result = await proxy.$http.post({
    url: "/order/refund1",
    params,
  });
  if (result.code === 1) {
    proxy.$success(result.msg);
    ApplyShow.value = false;
    location.reload();
  } else {
    proxy.$fail(result.msg);
    ApplyShow.value = false;
  }
};

// 确认收货
const OnConfirmReceive = async (id) => {
  orderid.value = id;
  proxy
    .$confirm({
      title: "确认收货",
      message: "是否确认收货",
    })
    .then(async () => {
      // 组装参数
      const params = {
        id: orderid.value,
        busid: business.value.id,
      };
      // 发起请求
      const result = await proxy.$http.post({
        url: "/order/receive",
        params,
      });
      if (result.code === 1) {
        proxy.$success(result.msg);
        location.reload();
      } else {
        proxy.$fail(result.msg);
      }
    })
    .catch(() => {});
};

// 评论弹出层
const OnCommentChange = async (product) => {
  // 回显评论数据
  CommentData.value = {
    id: product.id, // 订单商品id
    rate: parseInt(product.rate),
    comment: product.comment,
    status: product.comment ? true : false, // 若有评论数据 则表示已评论，没有则表示未评论
  };
  // 上传图片的数组
  let list = [];
  product.thumbs_text.map((url) => {
    list.push({ url });
  });
  thumbs.value = list;
  // 显示评论弹出层
  CommentShow.value = true;
};

// 提交评论
const OnCommentSubmit = async () => {
  // 组装参数
  const params = {
    id: CommentData.value.id,
    orderid: orderid.value,
    busid: business.value.id,
    comment: CommentData.value.comment,
    rate: CommentData.value.rate,
  };
  // 判断是否上传图片
  if (thumbs.value.length > 0) {
    let list = [];
    //图片追加到数组中
    thumbs.value.map((item) => item.file && list.push(item.file));
    params.thumbs = list;
  }
  // 结果集
  let result = {};
  if (params.thumbs) {
    // 多图上传 upload请求
    result = await proxy.$http.upload({
      url: "/order/comment",
      params,
    });
  } else {
    // post请求
    result = await proxy.$http.post({
      url: "/order/comment",
      params,
    });
  }
  // 处理请求结果
  if (result.code === 1) {
    proxy.$success(result.msg);
    // 关闭弹框
    CommentShow.value = false;
    // 刷新页面数据
    GetInfoData();
  } else {
    proxy.$fail(result.msg);
    // 关闭弹框
    CommentShow.value = false;
  }
};

// 跳转到物流详情页
const ToExpressInfo = (orderid) => {
  proxy.$router.push({ path: "/order/express", query: { orderid } });
};
</script>

<style scoped>
@import url("/assets/css/OrderInfo.css");
</style>